<#-- 异常号码分析 -->
<#include "../../common/_header.htm">
<div class="content-wrapper">
	<section class="content">
		<div class="row">
			<div class="bill-right">
				<form style="background:#fff;">
					<div class="box-header">
						<div class="row RowSearchWork">

									<div class="form-inline">
										<div class="form-group" style="margin-bottom: 13px">
			                                <label class="control-label">通话日期</label>
			                                <div class="input-group">
				                                <div class="input-icon-group">
				                                	<input type="text" class="form-control pull-right" name="createTime" id="starTime" autocomplete="off" placeholder="请选择通话时间" >
											        <span id="scan" class="glyphicon glyphicon-calendar"> 
											        </span>
											    </div>
										    </div>
			                            </div>
			                            <div class="form-group ml10">
			                            	<select class="form-control" name="beforeAndAfter" id="beforeAndAfter">
												<option value="1" selected>之后新增的号码</option>
												<option value="0">之后不联系的号码</option>
											</select>
			                            </div>
			                            <div class="form-group bill-buttonarea">
			                            	<input type="hidden" id="checkedAccount"/>
											<input type="button" class="btn btn-primary" onclick="abnormal.analysis();" value="分析" />
											<input type="button" class="btn btn-default" onclick="abnormal.reset();" value="重置" />
											<input type="button" class="btn btn-primary daobtn" onclick="abnormal.exportList('_table','异常号码分析');" value="导出" />
											<a style="display: none" target="_blank" id="_dow">dow</a>
										</div>
			                        </div>

						</div>
					</div>
						<div id="list_table">
							<table class="table table-bordered table-striped table-hide" id="_table">
								<thead>
								<tr>
									<th data-options="field:'code'">异常号码\机主号码</th>
									<th data-options="field:'name'">累计汇总</th>
								</tr>
								</thead>
								<tbody>
									<tr>
										<td colspan="2">暂无数据</td>
									</tr>
								</tbody>
							</table>
						</div>

				</form>
			<!--</div>-->
		</div>
	</section>
</div>
<script type="text/javascript" src="${ctx}/cus/base.js"></script>
<script type="text/javascript">
	var caseId=parent.caseId;
	$(document).ready(function(){
		 $(window).resize(function(){
			$('#_table').datagrid('resize',{
                height:($(window).height())-($('.box-header').outerHeight(true))-80,
			});
		});
        $("#starTime").val('2018-06-06');
        abnormal.analysis();
	});
    function _checkedCallback(){
        abnormal.analysis();
    }
    function detailDialog(servicePhone,partyNumber,startTime) {
        var beforeAndAfter = $("#beforeAndAfter").val();
        var param = {
            suspectPhone:servicePhone,
            suspectPhonePersonal:partyNumber,
            startTime:startTime,
            caseId:caseId,
            beforeAndAfter:beforeAndAfter,
        };
        if(parent.parent._checkedPhone.length>=1000){
            param.cardList="-1";//默认超过1000个节点为全选，不需要去后台传数据
        };
        var d = top.dialog({
            title : '异常号码分析详情',
            modal : true,
            url : '${ctx}/phoneAddress/abnormaldetailDialog',
            height : 800,
            width : 1500,
            data : param,
            onshow : function () {
            }
        });
        d.show();
        return false;
    }
	var idTmr;
	function  getExplorer() {
	    var explorer = window.navigator.userAgent ;
	    //ie
	    if (explorer.indexOf("MSIE") >= 0) {
	        return 'ie';
	    }
	    //firefox
	    else if (explorer.indexOf("Firefox") >= 0) {
	        return 'Firefox';
	    }
	    //Chrome
	    else if(explorer.indexOf("Chrome") >= 0){
	        return 'Chrome';
	    }
	    //Opera
	    else if(explorer.indexOf("Opera") >= 0){
	        return 'Opera';
	    }
	    //Safari
	    else if(explorer.indexOf("Safari") >= 0){
	        return 'Safari';
	    }
	}

	/* 日期选择器start */
    $("#starTime").datepicker({
        format: "yyyy-mm-dd",
        autoclose: true,
        language:'zh-CN',
        pickerPosition:"bottom-left"
    });
	/* 日期选择器end */
	var abnormal = {
		analysis : function(){
			/* if(parent.parent._checkedPhone.length < 2){
				 toastr.error("请选择两个或两个以上手机号","提示信息");
				 $('#_table').html("<thead>\n" +
                     "\t\t\t\t\t\t\t\t<tr>\n" +
                     "\t\t\t\t\t\t\t\t\t<th data-options=\"field:'code'\">异常联系人\\嫌疑人</th>\n" +
                     "\t\t\t\t\t\t\t\t\t<th data-options=\"field:'name'\">累计汇总</th>\n" +
                     "\t\t\t\t\t\t\t\t</tr>\n" +
                     "\t\t\t\t\t\t\t\t</thead>\n" +
                     "\t\t\t\t\t\t\t\t<tbody>\n" +
                     "\t\t\t\t\t\t\t\t<tr><td colspan=\"2\">暂无数据</td></tr>\n" +
                     "\t\t\t\t\t\t\t\t</tbody>");
				 return false;
			} */
			var startTime = $("#starTime").val();
			if(!startTime){
				 toastr.error("请选择通话时间","提示信息");
				 return false;
			}
			$("#_table").html("");
			/**参数封装**/
			var data = {
					"showType" : 0, 
					"caseId" : caseId,
					"startTime" : $("#starTime").val(),
					"checkedPhone" : parent.parent._checkedPhone.join(','),
					"beforeAndAfter" : $("#beforeAndAfter").val()
		    };
		    $.ajax({
		        type:"POST",
		        url:"${ctx}/abnormal/abnormalPhoneAnalysis",
		        data: JSON.stringify(data),
		        dataType:"json",
		        contentType:"application/json",
		        success:function(results){
                    if (results.result == "success") {
                        var phone = results.data[0];
                        var result = results.data[1];
                        var foote = results.data[2];
                        var col = new Array();
                        var arr = new Array();
                        //封装列
                        col.push({"field":"errorPerson", "title":"异常号码\\机主号码"});
                        $.each(phone,function(i,n) {
                            var str = {"field":n,"title":n,"align":"center",
                                formatter: function(value,row,index){
                                    if (row[value+"callNumber"]&&row[value+"callNumber"]!=0){
                                        var html = '';
                                        html  += '<a href="#" onclick="detailDialog(\''+row[value+"p"]+'\',\''+row.errorPerson+'\',\''+startTime+'\')">';
                                        html  += '<span cc="'+row[value+"callNumber"]+'">通话'+row[value+"callNumber"]+'次</span>';
                                        html  += '<span ss="'+row[value+"callSeconds"]+'">累计'+row[value+"callSeconds"]+'秒</span></a>';
                                        return html;
                                    } else if (row[value+"xtotalCallNumber"]&&row[value+"xtotalCallNumber"]!=0) {
                                        var html = '';
                                        html  += '<span cc="'+row[value+"xtotalCallNumber"]+'">通话'+row[value+"xtotalCallNumber"]+'次</span>';
                                        html  += '<span ss="'+row[value+"xtotalCallSeconds"]+'">累计'+row[value+"xtotalCallSeconds"]+'秒</span>';
                                        return html;
                                    } else {
                                        return "-";

                                    }
                                }
                            };
                            col.push(str);
                        });
                        col.push({"field":"xtotalCallNumber", "title":"汇总累计","align":"center",
                            formatter: function(value,row,index){
                                var sum = row.sum;
                                if (value&&value!=0){
                                    var html = '';
                                    html  += '<span cc="'+value+'">共通话'+value+'次</span>';
                                    html  += '<span ss="'+row.xtotalCallSeconds+'">累计'+row.xtotalCallSeconds+'秒</span>';
                                    return html;
                                } else if (row[sum+"xtotalCallSeconds"]&&row[sum+"xtotalCallSeconds"]!=0) {
                                    var html = '';
                                    html  += '<span >共通话'+row[sum+"xtotalCallNumber"]+'次</span>';
                                    html  += '<span ss="'+row[sum+"xtotalCallSeconds"]+'">累计'+row[sum+"xtotalCallSeconds"]+'秒</span>';
                                    return html;
                                }else {
                                    return "-";
                                }
                            }

                        });
                        //封装结果
                        $.each(result,function(ri,rval) {
                            var note ='{';
                            note  += '"errorPerson":"'+rval.exceptionPhone+'",';
                            $.each(phone,function(pi,p) {
                                $.each(rval.ecaps,function(ri,ecap) {
                                    if (p == ecap.suspectPhonePersonal){
                                        note  += '"'+ecap.suspectPhonePersonal+'":"'+ecap.suspectPhonePersonal+'",';
                                        note  += '"'+ecap.suspectPhonePersonal+'p":"'+p+'",';
                                        note  += '"'+ecap.suspectPhonePersonal+'callNumber":"'+ecap.callNumber+'",';
                                        note  += '"'+ecap.suspectPhonePersonal+'beginTime":"'+ecap.beginTime+'",';
                                        note  += '"'+ecap.suspectPhonePersonal+'callSeconds":"'+ecap.callSeconds+'",';
                                    }
                                });
                            });
                            note  += '"xtotalCallNumber":"'+rval.xtotalCallNumber+'",';
                            note  += '"xtotalCallSeconds":"'+rval.xtotalCallSeconds+'",';
                            note = note.substring(0,note.length-1);
                            note += '}';
                            arr.push(note);
                        });
                        //封装尾行
                        var not ='{';
                        not  += '"errorPerson":"汇总累计",';
                        $.each(foote,function(i,f) {
                            not  += '"'+f.exceptionPhone+'xtotalCallNumber":"'+f.xtotalCallNumber+'",';
                            not  += '"'+f.exceptionPhone+'":"'+f.exceptionPhone+'",';
                            not  += '"'+f.exceptionPhone+'xtotalCallSeconds":"'+f.xtotalCallSeconds+'",';
                        })
                        not = not.substring(0,not.length-1);
                        not += '}';
                        arr.push(not);
                        var jsonStr = '{"total":'+arr.length+',"rows":['+arr.join(",")+']}';

                        var data = $.parseJSON(jsonStr);
                        // $("#_table").append(html);
                        //重新加载表格
                        $('#_table').datagrid({
                            fitColumns:true,
                            singleSelect: true,
                            // fit: true,
                            singleSelect: true,
                            showFooter:true,
                            height:($(window).height())-($('.box-header').outerHeight(true))-80,
                            columns: [col],
                            //onClickRow: onClickRow, //单击事件
                        }).datagrid('loadData',data);

                    }
		        },
				error:function(err){
					toastr.error("数据加载失败","提示信息");
				}
		    });
		},
		chickShowType : function (value){
            if(value == 0){
                $("#list_table").show();
                $("#_d3").hide();
                $("#map").hide();
                abnormal.analysis();
            }else if(value == 1){
                $("#list_table").hide();
                $("#_d3").show();
                $("#map").hide();
            }else{
                $("#list_table").hide();
                $("#_d3").hide();
                $("#map").show();
            }
		},
		details : function (servicePhone,partyNumber,startTime){
			var beforeAndAfter = $("#beforeAndAfter").val();
			var title = '通话详情';
			parent.base.getView({
				url:"${ctx}/abnormal/abnormalDetailsInit?suspectPhone="+servicePhone+"&suspectPhonePersonal="+partyNumber+"&startTime="+startTime+"&beforeAndAfter="+beforeAndAfter+"&caseId="+caseId,
				success:function(result){
					bootbox.dialog({
						title:title,
						message:result,
						size:"large",
						boxCss:{"width":"1270px"},
						closeButton : true
					})
				}
			});
		},
		reset : function(){
			$("#starTime").val('');
		},
		exportList : function(tableid,excelName){
			if(getExplorer()=='ie') {
                var curTbl = document.getElementById(tableid);
                var oXL = new ActiveXObject("Excel.Application");

                //创建AX对象excel
                var oWB = oXL.Workbooks.Add();
                //获取workbook对象
                var xlsheet = oWB.Worksheets(1);
                //激活当前sheet
                var sel = document.body.createTextRange();
                sel.moveToElementText(curTbl);
                //把表格中的内容移到TextRange中
                sel.select;
                //全选TextRange中内容
                sel.execCommand("Copy");
                //复制TextRange中内容
                xlsheet.Paste();
                //粘贴到活动的EXCEL中
                oXL.Visible = true;
                //设置excel可见属性

                try {
                    var fname = oXL.Application.GetSaveAsFilename(excelName+".xls", "Excel Spreadsheets (*.xls), *.xls");
                } catch (e) {
                    print("Nested catch caught " + e);
                } finally {
                    oWB.SaveAs(fname);

                    oWB.Close(savechanges = false);
                    //xls.visible = false;
                    oXL.Quit();
                    oXL = null;
                    //结束excel进程，退出完成
                    //window.setInterval("Cleanup();",1);
                    idTmr = window.setInterval("Cleanup();", 1);
                }
            } else {
                tableToExcel(tableid,excelName)
            }
		}
	};
	function Cleanup() {
        window.clearInterval(idTmr);
        CollectGarbage();
    }
	/*
    template ： 定义文档的类型，相当于html页面中顶部的<!DOCTYPE> 声明。（个人理解，不确定）
    encodeURIComponent:解码
    unescape() 函数：对通过 escape() 编码的字符串进行解码。
    window.btoa(window.encodeURIComponent(str)):支持汉字进行解码。
    \w ：匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’
    replace()方法：用于在字符串中用一些字符替换另一些字符，或替换一个与正则表达式匹配的子串。
    {(\w+)}：匹配所有 {1个或更多字符} 形式的字符串；此处匹配输出内容是 “worksheet”
	    正则中的() ：是为了提取匹配的字符串。表达式中有几个()就有几个相应的匹配字符串。
	    讲解(/{(\w+)}/g, function(m, p) { return c[p]; } ：
     /{(\w+)}/g 匹配出所有形式为“{worksheet}”的字符串；
     function参数：  m  正则所匹配到的内容，即“worksheet”；
                     p  正则表达式中分组的内容,即“(\w+)”分组中匹配到的内容，为“worksheet”；
     c ：为object，见下图3
     c[p] : 为“worksheet”
	
	*/
	var tableToExcel = (function() {
	    var uri = 'data:application/vnd.ms-excel;base64,',
	    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
	    base64 = function(s) {
	        return window.btoa(unescape(encodeURIComponent(s)))
	    },
	    // 下面这段函数作用是：将template中的变量替换为页面内容ctx获取到的值
	    format = function(s, c) {
	            return s.replace(/{(\w+)}/g,
                      function(m, p) {
                          return c[p];
                      }
	            )
	    };
	    return function(table, name) {
	        if (!table.nodeType) {
	            table = document.getElementById(table)
	        }
	        // 获取表单的名字和表单查询的内容
	        var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
	        // format()函数：通过格式操作使任意类型的数据转换成一个字符串
	        // base64()：进行编码
	        document.getElementById("_dow").href = uri + base64(format(template, ctx));//必须是a标签，否则无法下载改名
	        document.getElementById("_dow").download = name;
	        document.getElementById("_dow").click();
	    }
	})();
	//转换日期格式(时间戳转换为datetime格式)
    function changeDateFormat(cellval) {
        var dateVal = cellval + "";
        if (cellval != null) {
            var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            
            var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
        }
    }
	//转换日期格式(时间戳转换为datetime格式)
    function changeDateFormat2(cellval) {
        var dateVal = cellval + "";
        if (cellval != null) {
            var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            
            return date.getFullYear() + "-" + month + "-" + currentDate;
        }
    }
</script>
<style>
	.bill-right {
		padding: 10px;
		padding-top: 5px;
	}
	input#starTime{
		width: 120px;
		height: 30px;
		border-radius: 0;
	}
	select#beforeAndAfter{
		width: 120px;
		height: 30px;
		padding-top: 2px;
		border-radius: 0;
	}
	.bill-buttonarea .btn {
		width: 70px;
		height: 30px;
		margin-right: 3px;
		line-height: 12px;
	}
	input.btn.btn-primary.daobtn{
		background-color: #23B7E5;
		border-color: #23B7E5;
	}
	.content-wrapper, .main-footer{
		margin-left: 0;
		padding: 0;
	}
	.control-label{
		font-size: 13px;
		font-weight: 400;
	}

	select#beforeAndAfter {
		margin-left: 20px;
		margin-right: 20px;
	}
	.btn-primary:active:focus{
		background-color: #4695ed;
		border-color: #4695ed;
	}
	.box-body .title{
		font-size:14px;
		font-weight:800;
		line-height:30px;
	}
	.box-body .casemanage-switch{
		margin:0;
	}
	.table-hide td{
		text-align:center;
		vertical-align:middle;
	}
	td span{ display:block;}
	.casemanage-switch .casemanage-list{
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
		border-top-left-radius: 5px;
		border-bottom-left-radius: 5px;
	}

	.btn-primary{
		background-color:#4695ed;
		border-color:#4695ed;
	}
	.btn-primary:hover, .btn-primary:active, .btn-primary.hover{
		background: #61a8f5;
		border-color: #61a8f5;
	}
	.btn-primary.focus, .btn-primary:focus{
		background-color:#4695ed;
		border-color:#4695ed;
	}
	.form-control{
		border-radius:4px;
		font-size: 12px;
	}
	.input-group .form-control:first-child{
		border-top-right-radius:4px;
		border-bottom-right-radius: 4px;
	}
	.form-control{
		border-radius:4px;
		border-color: #e4e4e4;
	}
	.input-group .form-control:first-child{
		border-top-right-radius:4px;
		border-bottom-right-radius: 4px;
	}
	.form-control:focus{
		border-color:#4695ed;
	}
	.form-control:hover{
		border-color:#4695ed;
	}
	.box{
		padding: 0;
	}
	.content {
		padding: 0 0 15px 25px;
	}
</style>
